<template>
  <el-date-picker
    v-model="time"
    :type="type"
    :shortcuts="state.dateOptions"
    :disabled-date="disabledDate"
    v-bind="attrsBind"
    @change="dateChange"
  >
    <template v-for="(index, name) in slots" #[name]="data">
      <slot :name="name" v-bind="data"></slot>
    </template>
  </el-date-picker>
</template>

<script setup lang="ts">
  defineOptions({ name: 'DateTimePicker' })
  import { computed, useAttrs, useSlots, watch, reactive } from 'vue'
  const props = defineProps({
    value: [String, Date, Array],
    plusTime: { type: Boolean, default: false },
    type: { type: String, default: 'date' },
    shortcuts: Array,
    isPickerOptions: { type: Boolean, default: false },
    /** 新增 config 对象，控制禁用日期 */
    config: {
      type: Object as () => {
        isEnable?: boolean
        minTime?: string
        maxTime?: string
      },
      default: () => ({ isEnable: false }),
    },
  })
  const emits = defineEmits(['update:modelValue', 'change'])
  const $attrs: any = useAttrs()
  const slots = useSlots()
  const time = computed({
    get: () => props.value,
    set: (val) => emits('update:modelValue', val),
  })
  /** 简化 attrs 构造 */
  const typeMap = {
    date: { 'value-format': 'YYYY-MM-DD', placeholder: '请选择日期' },
    dates: { 'value-format': 'YYYY-MM-DD', placeholder: '请选择日期' },
    week: { format: 'YYYY 第 ww 周', placeholder: '请选择周' },
    month: { 'value-format': 'YYYY-MM', format: 'YYYY-MM', placeholder: '请选择月' },
    months: { 'value-format': 'YYYY-MM', format: 'YYYY-MM', placeholder: '请选择月' },
    year: { 'value-format': 'YYYY', format: 'YYYY', placeholder: '请选择年' },
    years: { 'value-format': 'YYYY', format: 'YYYY', placeholder: '请选择年' },
    daterange: {
      'value-format': 'YYYY-MM-DD',
      'range-separator': '~',
      'start-placeholder': '请选择开始日期',
      'end-placeholder': '请选择结束日期',
    },
    monthrange: {
      'value-format': 'YYYY-MM',
      'range-separator': '~',
      'start-placeholder': '请选择开始月份',
      'end-placeholder': '请选择结束月份',
    },
    datetime: {
      format: 'YYYY-MM-DD HH:mm:ss',
      'value-format': 'YYYY-MM-DD HH:mm:ss',
      placeholder: '请选择日期时间',
    },
    datetimerange: {
      format: 'YYYY-MM-DD HH:mm:ss',
      'value-format': 'YYYY-MM-DD HH:mm:ss',
      'range-separator': '~',
      'start-placeholder': '请选择开始日期',
      'end-placeholder': '请选择结束日期',
    },
  }
  const attrsBind = computed(() => ({
    ...typeMap[props.type],
    ...$attrs,
  }))
  /** 快捷选项逻辑 */
  const state = reactive({ dateOptions: props.shortcuts })
  const getShortcuts = (type: string) => {
    const now = new Date()
    const day = 3600 * 1000 * 24
    const shortcutsMap: Record<string, any[]> = {
      date: [
        { text: '今天', value: now },
        { text: '昨天', value: () => new Date(now.getTime() - day) },
        { text: '一周前', value: () => new Date(now.getTime() - day * 7) },
      ],
      daterange: [
        { text: '最近一周', value: () => [new Date(now.getTime() - day * 7), now] },
        { text: '最近一个月', value: () => [new Date(now.getTime() - day * 30), now] },
        { text: '最近三个月', value: () => [new Date(now.getTime() - day * 90), now] },
      ],
      monthrange: [
        { text: '本月', value: [now, now] },
        { text: '今年至今', value: () => [new Date(new Date().getFullYear(), 0), now] },
        { text: '最近六个月', value: () => [new Date(now.setMonth(now.getMonth() - 6)), new Date()] },
      ],
      datetime: [
        { text: '今天', value: now },
        { text: '昨天', value: () => new Date(new Date().getTime() - day) },
        { text: '一周前', value: () => new Date(new Date().getTime() - day * 7) },
      ],
      datetimerange: [
        { text: '最近一周', value: () => [new Date(now.getTime() - day * 7), now] },
        { text: '最近一个月', value: () => [new Date(now.getTime() - day * 30), now] },
        { text: '最近三个月', value: () => [new Date(now.getTime() - day * 90), now] },
      ],
    }
    return shortcutsMap[type] || []
  }
  if (props.isPickerOptions) state.dateOptions = getShortcuts(props.type)
  watch(
    () => props.value,
    (val) => {
      time.value = val
    },
    { deep: true },
  )
  watch(
    () => props.shortcuts,
    (val) => {
      state.dateOptions = props.isPickerOptions ? getShortcuts(props.type) : val
    },
    { deep: true },
  )
  /** 动态禁用日期函数 */
  const disabledDate = (time: Date) => {
    const timeStamp = time.getTime()
    // 未开启禁用规则，全部可选
    if (!props.config?.isEnable) return false
    // 有配置时间范围，按范围禁用
    if (props.config.minTime || props.config.maxTime) {
      if (props.config.minTime && timeStamp < new Date(props.config.minTime).getTime()) {
        return true
      }
      if (props.config.maxTime && timeStamp > new Date(props.config.maxTime).getTime()) {
        return true
      }
      return false
    }
    // 启用禁用且没配置时间范围，默认禁用今天之前日期
    const todayStart = new Date(new Date().toLocaleDateString()).getTime()
    return timeStamp < todayStart
  }
  /** 日期变化处理 */
  const dateChange = (val: any) => {
    console.log('🔍 DateTimePicker dateChange:', {
      type: props.type,
      value: val,
      valueType: typeof val,
      isArray: Array.isArray(val),
    })

    if (props.type === 'daterange' && val) {
      let [startTime, endTime] = val
      if (props.plusTime) {
        startTime += ' 00:00:00'
        endTime += ' 23:59:59'
      }
      const result = [startTime, endTime]
      console.log('📅 daterange 处理结果:', result)
      emits('update:modelValue', result)
      emits('change', result)
    } else {
      // 对于其他类型（包括 datetimerange），直接传递 value-format 格式化后的值
      console.log('📅 其他类型处理结果:', val)
      emits('update:modelValue', val)
      emits('change', val)
    }
  }

  defineExpose({ state })
</script>
